Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [2]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [2]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[2]:
<matplotlib.image.AxesImage at 0x1dab8b69438>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [3]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[3]:
<matplotlib.image.AxesImage at 0x1dab93d12e8>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x1dab9436080>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [5]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[5]:
<matplotlib.image.AxesImage at 0x1dab948c780>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [6]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!

    
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
for (x,y,w,h) in faces:
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = image_with_detections[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color, (ex,ey), (ex+ew, ey+eh), (0,255,0), 3)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Out[6]:
<matplotlib.image.AxesImage at 0x1dab99ca048>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [7]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():

    # Extract the pre-trained detectors from an xml file
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
    
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # Convert the RGB  image to grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Detect the faces in image
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        
        for (x,y,w,h) in faces:
            # draw a rectangle around a face
            cv2.rectangle(frame, (x,y), (x+w,y+h),(255,0,0), 2)
    
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
            
            #Detect eyes in the roi and draw rectangles around them
            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color, (ex,ey), (ex+ew, ey+eh), (0,255,0), 2)
        
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
In [8]:
# Call the laptop camera face/eye detector function above
laptop_camera_go()

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [9]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[9]:
<matplotlib.image.AxesImage at 0x1daba77f898>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [10]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 12
Out[10]:
<matplotlib.image.AxesImage at 0x1dab9809278>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [14]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!


denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise, None, 15, 15, 9, 25)

fig = plt.figure(figsize=(8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('NL denoised image')
ax1.imshow(denoised_image)
Out[14]:
<matplotlib.image.AxesImage at 0x1daba8b9898>
In [15]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result
#Convert RGB to gray color spaces
gray_denoised = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

#Extract the pre-trained face detector
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

#Detect faces
faces = face_cascade.detectMultiScale(gray_denoised, 4, 6)

# Print #detected faces
print('Number of faces detected: ', faces.shape[0])

# Make a copy of denoised image
denoised_img_w_detections = np.copy(denoised_image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box of a face
    cv2.rectangle(denoised_img_w_detections, (x,y), (x+w, y+h), (255,0,0), 3)
    
fig = plt.figure(figsize=(8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Denoised image with Face Detections')
ax1.imshow(denoised_img_w_detections)
Number of faces detected:  13
Out[15]:
<matplotlib.image.AxesImage at 0x1daba963d30>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [16]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[16]:
<matplotlib.image.AxesImage at 0x1daba9d1b00>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [17]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
kernel_width = 4
kernel = np.ones((kernel_width,kernel_width), np.float32)/(kernel_width**2)
# since the kernel size is 4x4 which is not of odd number, we cannot use teh default anchor--at the center of the kernel
filtered_gray = cv2.filter2D(gray, ddepth=-1, kernel=kernel, anchor=(1,1))

## TODO: Then perform Canny edge detection and display the output
#Perform Canny edge detection
pre_filtering_edges = cv2.Canny(filtered_gray, 100, 200)

#Dilate the image edges
pre_filtering_edges = cv2.dilate(pre_filtering_edges, None)

#Plot the RGB and edge-detected images before and after filtering
fig = plt.figure(figsize=(15,15))

ax1 = fig.add_subplot(131)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original image')
ax1.imshow(image)

ax2 = fig.add_subplot(132)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Canny edges without pre-filtering')
ax2.imshow(edges, cmap='gray')


ax3 = fig.add_subplot(133)
ax3.set_xticks([])
ax3.set_yticks([])
ax3.set_title('Canny edges with pre-filtering')
ax3.imshow(pre_filtering_edges, cmap='gray')
Out[17]:
<matplotlib.image.AxesImage at 0x1dabd8b1dd8>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [18]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[18]:
<matplotlib.image.AxesImage at 0x1dabb284898>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [19]:
## TODO: Implement face detection
#Convert RGB to gray color spaces
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

#Extract the pre-trained face detector
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

#Detect faces
faces = face_cascade.detectMultiScale(gray, 1.5, 4)

# Print #detected faces
print('Number of faces detected: ', faces.shape[0])


## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
kernel_width = 50
kernel = np.ones((kernel_width,kernel_width), np.float32)/(kernel_width**2)


blurred_face_img = np.copy(image)

for (x,y,w,h) in faces:
    roi_color = blurred_face_img[y:y+h, x:x+w]
    blurred_face_img[y:y+h, x:x+w] = cv2.filter2D(roi_color, ddepth=-1, kernel=kernel)
    
## Display
image_w_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box of a face
    cv2.rectangle(image_w_detections, (x,y), (x+w, y+h), (255,0,0), 10)
    
fig = plt.figure(figsize=(15,15))
ax1 = fig.add_subplot(131)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original image')
ax1.imshow(image)

ax2 = fig.add_subplot(132)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Image with Face Detections')
ax2.imshow(image_w_detections)


ax3 = fig.add_subplot(133)
ax3.set_xticks([])
ax3.set_yticks([])
ax3.set_title('Image with Blurred Face')
ax3.imshow(blurred_face_img)
plt.tight_layout()
Number of faces detected:  1

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [20]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_go():
    
    # Extract the pre-trained detectors from an xml file
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    
    # Mean kernel
    kernel_width = 50
    kernel = np.ones((kernel_width,kernel_width), np.float32)/(kernel_width**2)
    
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Convert the RGB  image to grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Detect the faces in image
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        
        for (x,y,w,h) in faces:
            roi_color = frame[y:y+h, x:x+w]    
            frame[y:y+h, x:x+w] = cv2.filter2D(roi_color, ddepth=-1, kernel=kernel)        
        
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [21]:
# Run laptop identity hider
laptop_camera_go()

Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [3]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
Using TensorFlow backend.
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [23]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [7]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
from keras.regularizers import l2, l1, l1_l2


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

#parameters
pool_size = 2
strides=(1,1)
kernel_reg=None

model = Sequential()

model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', 
                 kernel_regularizer=kernel_reg, input_shape=(96, 96, 1)))
model.add(MaxPooling2D(pool_size=pool_size))

model.add(Conv2D(filters=32, kernel_size=2, strides=strides, padding='same',
                 activation='relu',kernel_regularizer=kernel_reg))
model.add(MaxPooling2D(pool_size=pool_size))

model.add(Conv2D(filters=64, kernel_size=2, strides=strides,padding='same',
                 activation='relu',kernel_regularizer=kernel_reg))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.3))

model.add(Flatten())

model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(30, activation=None))


# Summarize the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 16)        80        
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 32)        2080      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 64)        8256      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 9216)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 500)               4608500   
_________________________________________________________________
dropout_2 (Dropout)          (None, 500)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 30)                15030     
=================================================================
Total params: 4,633,946.0
Trainable params: 4,633,946.0
Non-trainable params: 0.0
_________________________________________________________________

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [38]:
from keras.callbacks import History, ModelCheckpoint, CSVLogger, EarlyStopping
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam

## TODO: Compile the model
model.compile(loss='mean_squared_error', optimizer=Nadam(), metrics=['accuracy'])

# Define callback
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best_ndam.hdf5', 
                               verbose=1, save_best_only=True)
history = History()
csv_logger = CSVLogger('training_log_nadam.log')

early_stopping = EarlyStopping(monitor='val_loss', min_delta=0,
                              patience=15, verbose=0, mode='auto')

## TODO: Train the model
epochs = 150
batch_size = 128

model.fit(X_train, y_train, validation_split=0.2,epochs=epochs,
         batch_size=batch_size, verbose=2,
         callbacks=[history, checkpointer, csv_logger, early_stopping])

## TODO: Save the model as model.h5
model.save('my_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/150
Epoch 00000: val_loss improved from inf to 0.01056, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.1762 - acc: 0.3213 - val_loss: 0.0106 - val_acc: 0.6963
Epoch 2/150
Epoch 00001: val_loss improved from 0.01056 to 0.00883, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0250 - acc: 0.4223 - val_loss: 0.0088 - val_acc: 0.6963
Epoch 3/150
Epoch 00002: val_loss did not improve
14s - loss: 0.0210 - acc: 0.4801 - val_loss: 0.0110 - val_acc: 0.6963
Epoch 4/150
Epoch 00003: val_loss improved from 0.00883 to 0.00480, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.0177 - acc: 0.4796 - val_loss: 0.0048 - val_acc: 0.6963
Epoch 5/150
Epoch 00004: val_loss improved from 0.00480 to 0.00444, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0152 - acc: 0.4836 - val_loss: 0.0044 - val_acc: 0.6963
Epoch 6/150
Epoch 00005: val_loss did not improve
14s - loss: 0.0138 - acc: 0.5263 - val_loss: 0.0048 - val_acc: 0.6963
Epoch 7/150
Epoch 00006: val_loss did not improve
13s - loss: 0.0125 - acc: 0.5286 - val_loss: 0.0046 - val_acc: 0.6986
Epoch 8/150
Epoch 00007: val_loss did not improve
14s - loss: 0.0124 - acc: 0.5374 - val_loss: 0.0097 - val_acc: 0.7009
Epoch 9/150
Epoch 00008: val_loss improved from 0.00444 to 0.00401, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0124 - acc: 0.5572 - val_loss: 0.0040 - val_acc: 0.7056
Epoch 10/150
Epoch 00009: val_loss improved from 0.00401 to 0.00365, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0099 - acc: 0.5718 - val_loss: 0.0036 - val_acc: 0.7079
Epoch 11/150
Epoch 00010: val_loss did not improve
13s - loss: 0.0086 - acc: 0.5643 - val_loss: 0.0086 - val_acc: 0.7103
Epoch 12/150
Epoch 00011: val_loss did not improve
13s - loss: 0.0090 - acc: 0.5940 - val_loss: 0.0068 - val_acc: 0.7056
Epoch 13/150
Epoch 00012: val_loss did not improve
13s - loss: 0.0087 - acc: 0.6034 - val_loss: 0.0066 - val_acc: 0.7079
Epoch 14/150
Epoch 00013: val_loss did not improve
15s - loss: 0.0081 - acc: 0.6011 - val_loss: 0.0055 - val_acc: 0.6916
Epoch 15/150
Epoch 00014: val_loss improved from 0.00365 to 0.00295, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.0070 - acc: 0.5993 - val_loss: 0.0030 - val_acc: 0.7103
Epoch 16/150
Epoch 00015: val_loss did not improve
15s - loss: 0.0082 - acc: 0.6051 - val_loss: 0.0049 - val_acc: 0.7056
Epoch 17/150
Epoch 00016: val_loss did not improve
15s - loss: 0.0067 - acc: 0.6157 - val_loss: 0.0056 - val_acc: 0.7079
Epoch 18/150
Epoch 00017: val_loss did not improve
15s - loss: 0.0071 - acc: 0.6232 - val_loss: 0.0036 - val_acc: 0.7079
Epoch 19/150
Epoch 00018: val_loss improved from 0.00295 to 0.00254, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0062 - acc: 0.6379 - val_loss: 0.0025 - val_acc: 0.7056
Epoch 20/150
Epoch 00019: val_loss did not improve
13s - loss: 0.0065 - acc: 0.6489 - val_loss: 0.0027 - val_acc: 0.7103
Epoch 21/150
Epoch 00020: val_loss did not improve
13s - loss: 0.0058 - acc: 0.6565 - val_loss: 0.0026 - val_acc: 0.7150
Epoch 22/150
Epoch 00021: val_loss did not improve
13s - loss: 0.0061 - acc: 0.6519 - val_loss: 0.0041 - val_acc: 0.7056
Epoch 23/150
Epoch 00022: val_loss improved from 0.00254 to 0.00247, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0056 - acc: 0.6530 - val_loss: 0.0025 - val_acc: 0.7079
Epoch 24/150
Epoch 00023: val_loss did not improve
13s - loss: 0.0055 - acc: 0.6472 - val_loss: 0.0034 - val_acc: 0.7150
Epoch 25/150
Epoch 00024: val_loss did not improve
14s - loss: 0.0051 - acc: 0.6630 - val_loss: 0.0025 - val_acc: 0.7103
Epoch 26/150
Epoch 00025: val_loss improved from 0.00247 to 0.00227, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0046 - acc: 0.6840 - val_loss: 0.0023 - val_acc: 0.7313
Epoch 27/150
Epoch 00026: val_loss did not improve
13s - loss: 0.0051 - acc: 0.6554 - val_loss: 0.0023 - val_acc: 0.7150
Epoch 28/150
Epoch 00027: val_loss improved from 0.00227 to 0.00218, saving model to saved_models/weights.best_ndam.hdf5
13s - loss: 0.0047 - acc: 0.6723 - val_loss: 0.0022 - val_acc: 0.7196
Epoch 29/150
Epoch 00028: val_loss improved from 0.00218 to 0.00210, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0047 - acc: 0.6711 - val_loss: 0.0021 - val_acc: 0.7453
Epoch 30/150
Epoch 00029: val_loss did not improve
14s - loss: 0.0049 - acc: 0.6939 - val_loss: 0.0023 - val_acc: 0.7313
Epoch 31/150
Epoch 00030: val_loss did not improve
16s - loss: 0.0048 - acc: 0.6834 - val_loss: 0.0026 - val_acc: 0.7079
Epoch 32/150
Epoch 00031: val_loss improved from 0.00210 to 0.00208, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0045 - acc: 0.6846 - val_loss: 0.0021 - val_acc: 0.7360
Epoch 33/150
Epoch 00032: val_loss did not improve
16s - loss: 0.0039 - acc: 0.6933 - val_loss: 0.0031 - val_acc: 0.7336
Epoch 34/150
Epoch 00033: val_loss did not improve
15s - loss: 0.0040 - acc: 0.6968 - val_loss: 0.0026 - val_acc: 0.7336
Epoch 35/150
Epoch 00034: val_loss improved from 0.00208 to 0.00198, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.0037 - acc: 0.7015 - val_loss: 0.0020 - val_acc: 0.7360
Epoch 36/150
Epoch 00035: val_loss did not improve
15s - loss: 0.0041 - acc: 0.6933 - val_loss: 0.0023 - val_acc: 0.7243
Epoch 37/150
Epoch 00036: val_loss did not improve
15s - loss: 0.0036 - acc: 0.7144 - val_loss: 0.0020 - val_acc: 0.7290
Epoch 38/150
Epoch 00037: val_loss improved from 0.00198 to 0.00192, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.0036 - acc: 0.7120 - val_loss: 0.0019 - val_acc: 0.7220
Epoch 39/150
Epoch 00038: val_loss did not improve
15s - loss: 0.0035 - acc: 0.7027 - val_loss: 0.0020 - val_acc: 0.7290
Epoch 40/150
Epoch 00039: val_loss did not improve
16s - loss: 0.0040 - acc: 0.7103 - val_loss: 0.0020 - val_acc: 0.7243
Epoch 41/150
Epoch 00040: val_loss did not improve
16s - loss: 0.0034 - acc: 0.7097 - val_loss: 0.0020 - val_acc: 0.7243
Epoch 42/150
Epoch 00041: val_loss improved from 0.00192 to 0.00186, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0032 - acc: 0.7167 - val_loss: 0.0019 - val_acc: 0.7266
Epoch 43/150
Epoch 00042: val_loss did not improve
16s - loss: 0.0032 - acc: 0.7284 - val_loss: 0.0020 - val_acc: 0.7266
Epoch 44/150
Epoch 00043: val_loss did not improve
15s - loss: 0.0032 - acc: 0.7161 - val_loss: 0.0020 - val_acc: 0.7243
Epoch 45/150
Epoch 00044: val_loss did not improve
15s - loss: 0.0034 - acc: 0.7348 - val_loss: 0.0034 - val_acc: 0.7336
Epoch 46/150
Epoch 00045: val_loss did not improve
16s - loss: 0.0034 - acc: 0.7331 - val_loss: 0.0026 - val_acc: 0.7290
Epoch 47/150
Epoch 00046: val_loss did not improve
16s - loss: 0.0033 - acc: 0.7255 - val_loss: 0.0022 - val_acc: 0.7336
Epoch 48/150
Epoch 00047: val_loss improved from 0.00186 to 0.00175, saving model to saved_models/weights.best_ndam.hdf5
18s - loss: 0.0030 - acc: 0.7202 - val_loss: 0.0018 - val_acc: 0.7336
Epoch 49/150
Epoch 00048: val_loss did not improve
16s - loss: 0.0030 - acc: 0.7325 - val_loss: 0.0018 - val_acc: 0.7336
Epoch 50/150
Epoch 00049: val_loss did not improve
16s - loss: 0.0028 - acc: 0.7132 - val_loss: 0.0021 - val_acc: 0.7360
Epoch 51/150
Epoch 00050: val_loss did not improve
16s - loss: 0.0028 - acc: 0.7401 - val_loss: 0.0020 - val_acc: 0.7383
Epoch 52/150
Epoch 00051: val_loss did not improve
17s - loss: 0.0029 - acc: 0.7383 - val_loss: 0.0018 - val_acc: 0.7360
Epoch 53/150
Epoch 00052: val_loss did not improve
16s - loss: 0.0027 - acc: 0.7319 - val_loss: 0.0018 - val_acc: 0.7313
Epoch 54/150
Epoch 00053: val_loss improved from 0.00175 to 0.00175, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0027 - acc: 0.7325 - val_loss: 0.0017 - val_acc: 0.7383
Epoch 55/150
Epoch 00054: val_loss did not improve
18s - loss: 0.0028 - acc: 0.7214 - val_loss: 0.0019 - val_acc: 0.7360
Epoch 56/150
Epoch 00055: val_loss did not improve
20s - loss: 0.0026 - acc: 0.7360 - val_loss: 0.0018 - val_acc: 0.7500
Epoch 57/150
Epoch 00056: val_loss improved from 0.00175 to 0.00165, saving model to saved_models/weights.best_ndam.hdf5
21s - loss: 0.0026 - acc: 0.7307 - val_loss: 0.0016 - val_acc: 0.7430
Epoch 58/150
Epoch 00057: val_loss did not improve
16s - loss: 0.0026 - acc: 0.7412 - val_loss: 0.0018 - val_acc: 0.7453
Epoch 59/150
Epoch 00058: val_loss did not improve
16s - loss: 0.0026 - acc: 0.7354 - val_loss: 0.0018 - val_acc: 0.7383
Epoch 60/150
Epoch 00059: val_loss did not improve
16s - loss: 0.0026 - acc: 0.7424 - val_loss: 0.0025 - val_acc: 0.7407
Epoch 61/150
Epoch 00060: val_loss improved from 0.00165 to 0.00162, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0024 - acc: 0.7407 - val_loss: 0.0016 - val_acc: 0.7360
Epoch 62/150
Epoch 00061: val_loss improved from 0.00162 to 0.00161, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0025 - acc: 0.7412 - val_loss: 0.0016 - val_acc: 0.7383
Epoch 63/150
Epoch 00062: val_loss did not improve
16s - loss: 0.0024 - acc: 0.7459 - val_loss: 0.0017 - val_acc: 0.7453
Epoch 64/150
Epoch 00063: val_loss did not improve
16s - loss: 0.0023 - acc: 0.7500 - val_loss: 0.0019 - val_acc: 0.7360
Epoch 65/150
Epoch 00064: val_loss did not improve
16s - loss: 0.0023 - acc: 0.7494 - val_loss: 0.0017 - val_acc: 0.7383
Epoch 66/150
Epoch 00065: val_loss improved from 0.00161 to 0.00156, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0022 - acc: 0.7564 - val_loss: 0.0016 - val_acc: 0.7336
Epoch 67/150
Epoch 00066: val_loss did not improve
16s - loss: 0.0023 - acc: 0.7477 - val_loss: 0.0018 - val_acc: 0.7453
Epoch 68/150
Epoch 00067: val_loss did not improve
16s - loss: 0.0023 - acc: 0.7424 - val_loss: 0.0016 - val_acc: 0.7430
Epoch 69/150
Epoch 00068: val_loss did not improve
16s - loss: 0.0022 - acc: 0.7576 - val_loss: 0.0017 - val_acc: 0.7664
Epoch 70/150
Epoch 00069: val_loss did not improve
16s - loss: 0.0021 - acc: 0.7506 - val_loss: 0.0019 - val_acc: 0.7313
Epoch 71/150
Epoch 00070: val_loss improved from 0.00156 to 0.00154, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0021 - acc: 0.7401 - val_loss: 0.0015 - val_acc: 0.7500
Epoch 72/150
Epoch 00071: val_loss did not improve
16s - loss: 0.0022 - acc: 0.7646 - val_loss: 0.0020 - val_acc: 0.7477
Epoch 73/150
Epoch 00072: val_loss did not improve
16s - loss: 0.0021 - acc: 0.7523 - val_loss: 0.0017 - val_acc: 0.7477
Epoch 74/150
Epoch 00073: val_loss did not improve
17s - loss: 0.0020 - acc: 0.7681 - val_loss: 0.0023 - val_acc: 0.7570
Epoch 75/150
Epoch 00074: val_loss did not improve
16s - loss: 0.0021 - acc: 0.7629 - val_loss: 0.0018 - val_acc: 0.7500
Epoch 76/150
Epoch 00075: val_loss did not improve
16s - loss: 0.0020 - acc: 0.7599 - val_loss: 0.0016 - val_acc: 0.7453
Epoch 77/150
Epoch 00076: val_loss improved from 0.00154 to 0.00145, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0019 - acc: 0.7535 - val_loss: 0.0014 - val_acc: 0.7407
Epoch 78/150
Epoch 00077: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7482 - val_loss: 0.0016 - val_acc: 0.7477
Epoch 79/150
Epoch 00078: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7599 - val_loss: 0.0017 - val_acc: 0.7453
Epoch 80/150
Epoch 00079: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7582 - val_loss: 0.0015 - val_acc: 0.7523
Epoch 81/150
Epoch 00080: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7675 - val_loss: 0.0016 - val_acc: 0.7383
Epoch 82/150
Epoch 00081: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7804 - val_loss: 0.0016 - val_acc: 0.7407
Epoch 83/150
Epoch 00082: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7669 - val_loss: 0.0016 - val_acc: 0.7570
Epoch 84/150
Epoch 00083: val_loss did not improve
16s - loss: 0.0018 - acc: 0.7664 - val_loss: 0.0015 - val_acc: 0.7804
Epoch 85/150
Epoch 00084: val_loss did not improve
16s - loss: 0.0018 - acc: 0.7839 - val_loss: 0.0018 - val_acc: 0.7640
Epoch 86/150
Epoch 00085: val_loss did not improve
16s - loss: 0.0018 - acc: 0.7734 - val_loss: 0.0019 - val_acc: 0.7734
Epoch 87/150
Epoch 00086: val_loss did not improve
16s - loss: 0.0017 - acc: 0.7745 - val_loss: 0.0021 - val_acc: 0.7477
Epoch 88/150
Epoch 00087: val_loss did not improve
16s - loss: 0.0019 - acc: 0.7687 - val_loss: 0.0015 - val_acc: 0.7523
Epoch 89/150
Epoch 00088: val_loss did not improve
16s - loss: 0.0017 - acc: 0.7734 - val_loss: 0.0016 - val_acc: 0.7664
Epoch 90/150
Epoch 00089: val_loss did not improve
17s - loss: 0.0017 - acc: 0.7634 - val_loss: 0.0018 - val_acc: 0.7453
Epoch 91/150
Epoch 00090: val_loss did not improve
18s - loss: 0.0017 - acc: 0.7699 - val_loss: 0.0015 - val_acc: 0.7523
Epoch 92/150
Epoch 00091: val_loss did not improve
17s - loss: 0.0017 - acc: 0.7716 - val_loss: 0.0015 - val_acc: 0.7874
Epoch 93/150
Epoch 00092: val_loss improved from 0.00145 to 0.00140, saving model to saved_models/weights.best_ndam.hdf5
16s - loss: 0.0017 - acc: 0.7611 - val_loss: 0.0014 - val_acc: 0.7804
Epoch 94/150
Epoch 00093: val_loss did not improve
16s - loss: 0.0016 - acc: 0.7763 - val_loss: 0.0015 - val_acc: 0.7664
Epoch 95/150
Epoch 00094: val_loss did not improve
16s - loss: 0.0016 - acc: 0.7699 - val_loss: 0.0016 - val_acc: 0.7734
Epoch 96/150
Epoch 00095: val_loss did not improve
16s - loss: 0.0016 - acc: 0.7728 - val_loss: 0.0016 - val_acc: 0.7827
Epoch 97/150
Epoch 00096: val_loss improved from 0.00140 to 0.00138, saving model to saved_models/weights.best_ndam.hdf5
18s - loss: 0.0015 - acc: 0.7804 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 98/150
Epoch 00097: val_loss improved from 0.00138 to 0.00135, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0016 - acc: 0.7763 - val_loss: 0.0014 - val_acc: 0.7874
Epoch 99/150
Epoch 00098: val_loss did not improve
14s - loss: 0.0016 - acc: 0.7880 - val_loss: 0.0018 - val_acc: 0.7664
Epoch 100/150
Epoch 00099: val_loss did not improve
14s - loss: 0.0016 - acc: 0.7704 - val_loss: 0.0014 - val_acc: 0.7780
Epoch 101/150
Epoch 00100: val_loss did not improve
14s - loss: 0.0015 - acc: 0.7891 - val_loss: 0.0014 - val_acc: 0.7710
Epoch 102/150
Epoch 00101: val_loss improved from 0.00135 to 0.00133, saving model to saved_models/weights.best_ndam.hdf5
15s - loss: 0.0016 - acc: 0.7897 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 103/150
Epoch 00102: val_loss did not improve
14s - loss: 0.0015 - acc: 0.7886 - val_loss: 0.0014 - val_acc: 0.7664
Epoch 104/150
Epoch 00103: val_loss did not improve
14s - loss: 0.0015 - acc: 0.7926 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 105/150
Epoch 00104: val_loss did not improve
14s - loss: 0.0015 - acc: 0.7985 - val_loss: 0.0014 - val_acc: 0.7500
Epoch 106/150
Epoch 00105: val_loss did not improve
14s - loss: 0.0015 - acc: 0.7798 - val_loss: 0.0014 - val_acc: 0.7850
Epoch 107/150
Epoch 00106: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7874 - val_loss: 0.0018 - val_acc: 0.7780
Epoch 108/150
Epoch 00107: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7985 - val_loss: 0.0015 - val_acc: 0.7407
Epoch 109/150
Epoch 00108: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7833 - val_loss: 0.0014 - val_acc: 0.7780
Epoch 110/150
Epoch 00109: val_loss did not improve
15s - loss: 0.0014 - acc: 0.7810 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 111/150
Epoch 00110: val_loss did not improve
14s - loss: 0.0013 - acc: 0.7886 - val_loss: 0.0014 - val_acc: 0.7780
Epoch 112/150
Epoch 00111: val_loss improved from 0.00133 to 0.00132, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0014 - acc: 0.7973 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 113/150
Epoch 00112: val_loss improved from 0.00132 to 0.00131, saving model to saved_models/weights.best_ndam.hdf5
14s - loss: 0.0013 - acc: 0.7874 - val_loss: 0.0013 - val_acc: 0.7710
Epoch 114/150
Epoch 00113: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7903 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 115/150
Epoch 00114: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7856 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 116/150
Epoch 00115: val_loss did not improve
14s - loss: 0.0014 - acc: 0.7757 - val_loss: 0.0015 - val_acc: 0.7523
Epoch 117/150
Epoch 00116: val_loss did not improve
14s - loss: 0.0013 - acc: 0.8014 - val_loss: 0.0015 - val_acc: 0.7617
Epoch 118/150
Epoch 00117: val_loss did not improve
14s - loss: 0.0013 - acc: 0.7874 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 119/150
Epoch 00118: val_loss did not improve
13s - loss: 0.0013 - acc: 0.7845 - val_loss: 0.0014 - val_acc: 0.7897
Epoch 120/150
Epoch 00119: val_loss did not improve
14s - loss: 0.0013 - acc: 0.7845 - val_loss: 0.0016 - val_acc: 0.7757
Epoch 121/150
Epoch 00120: val_loss did not improve
13s - loss: 0.0013 - acc: 0.7862 - val_loss: 0.0013 - val_acc: 0.7640
Epoch 122/150
Epoch 00121: val_loss did not improve
14s - loss: 0.0013 - acc: 0.8002 - val_loss: 0.0014 - val_acc: 0.7710
Epoch 123/150
Epoch 00122: val_loss did not improve
13s - loss: 0.0013 - acc: 0.7985 - val_loss: 0.0013 - val_acc: 0.7570
Epoch 124/150
Epoch 00123: val_loss did not improve
13s - loss: 0.0013 - acc: 0.7874 - val_loss: 0.0014 - val_acc: 0.7570
Epoch 125/150
Epoch 00124: val_loss did not improve
15s - loss: 0.0013 - acc: 0.7915 - val_loss: 0.0016 - val_acc: 0.7850
Epoch 126/150
Epoch 00125: val_loss did not improve
15s - loss: 0.0013 - acc: 0.8032 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 127/150
Epoch 00126: val_loss did not improve
13s - loss: 0.0013 - acc: 0.7815 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 128/150
Epoch 00127: val_loss did not improve
14s - loss: 0.0013 - acc: 0.7780 - val_loss: 0.0014 - val_acc: 0.7640
Epoch 129/150
Epoch 00128: val_loss did not improve
14s - loss: 0.0012 - acc: 0.7915 - val_loss: 0.0017 - val_acc: 0.7757
In [39]:
model.load_weights('saved_models/weights.best_ndam.hdf5')

history.history
Out[39]:
{'acc': [0.32126168196446425,
  0.42231308383362315,
  0.48014018747294063,
  0.47955607476635514,
  0.48364485981308414,
  0.52628504672897192,
  0.52862149504857647,
  0.53738317757009346,
  0.55724299009715283,
  0.5718457949495761,
  0.56425233644859818,
  0.59404205663181908,
  0.60338785102434245,
  0.60105140242621158,
  0.59929906597761351,
  0.60514018691588789,
  0.61565420616452937,
  0.62324766410845467,
  0.63785046728971961,
  0.64894859757378842,
  0.65654205663181908,
  0.65186915943555745,
  0.65303738262051736,
  0.64719626223929572,
  0.66296729027667889,
  0.68399532710280375,
  0.65537383177570097,
  0.67231308411214952,
  0.67114485981308414,
  0.69392523420191254,
  0.6834112155103238,
  0.68457943980938918,
  0.69334112149532712,
  0.69684579383547063,
  0.70151869214583784,
  0.69334112205237985,
  0.71436915943555745,
  0.71203270972332111,
  0.70268691533079775,
  0.71028037383177567,
  0.70969626223929572,
  0.71670560691958274,
  0.72838785102434245,
  0.71612149532710279,
  0.73481308411214952,
  0.73306074766355145,
  0.72546728971962615,
  0.72021028037383172,
  0.7324766360710715,
  0.71320093457943923,
  0.74007009290089121,
  0.7383177575663985,
  0.73189252280743322,
  0.7324766360710715,
  0.72137850467289721,
  0.73598130785416216,
  0.73072429906542058,
  0.74123831831406206,
  0.73539719681873494,
  0.74240654261312755,
  0.7406542050504239,
  0.74123831831406206,
  0.74591121495327106,
  0.74999999944294726,
  0.74941588785046731,
  0.75642523420191254,
  0.74766355140186913,
  0.74240654261312755,
  0.75759345794392519,
  0.75058411270658543,
  0.74007009290089121,
  0.76460280429537053,
  0.75233644859813087,
  0.76810747719256678,
  0.76285046784677235,
  0.75992990598500332,
  0.75350467289719625,
  0.74824766410845467,
  0.75992990709910879,
  0.75817757009345799,
  0.76752336504303409,
  0.78037383177570097,
  0.76693925233644855,
  0.76635514018691586,
  0.78387850522994995,
  0.77336448653836121,
  0.77453271028037385,
  0.76869158934209947,
  0.77336448542425562,
  0.76343457888219957,
  0.76985981308411211,
  0.77161214897565755,
  0.76109813084112155,
  0.77628504728602477,
  0.76985981308411211,
  0.77278037327472293,
  0.7803738323327537,
  0.77628504617191918,
  0.78796728971962615,
  0.77044392467659206,
  0.78913551346163879,
  0.78971962672527707,
  0.78855140186915884,
  0.79264018747294063,
  0.79848130896826774,
  0.77978971906911543,
  0.7873831781271462,
  0.79848130841121501,
  0.78329439252336452,
  0.78095794336818092,
  0.78855140242621158,
  0.79731308355509678,
  0.7873831781271462,
  0.79030373887480976,
  0.78563084167854813,
  0.77570093402238649,
  0.8014018697159313,
  0.78738317757009346,
  0.78446261737948264,
  0.7844626168224299,
  0.78621495327102808,
  0.80023364430276034,
  0.79848130841121501,
  0.78738317701304072,
  0.79147196317387514,
  0.8031542050504239,
  0.78154205607476634,
  0.77803738262051736,
  0.79147196317387514],
 'loss': [0.17621224467581678,
  0.024978204081966496,
  0.020961929304159691,
  0.01774136192017348,
  0.01522292614540207,
  0.013775179589115014,
  0.012548340458388084,
  0.012366406158239486,
  0.012417619499578097,
  0.0099181321789031836,
  0.0086346160637858875,
  0.0089673416549775082,
  0.0087163093995964412,
  0.0080680198897825229,
  0.0070304453816856733,
  0.0081596240906097062,
  0.0066790096853450633,
  0.0071309290382419238,
  0.0062478222518671895,
  0.0065490568805242257,
  0.0058344248290582799,
  0.0061367233153258533,
  0.005600857879165734,
  0.0054734645837865702,
  0.0050915179591382222,
  0.0045684389030195283,
  0.0050939390148584535,
  0.0046565067414716579,
  0.0046914476753325664,
  0.0049420992199714492,
  0.0048186878725955977,
  0.0044915308570924488,
  0.0038540234841475977,
  0.0039825028996636098,
  0.0037379386512754117,
  0.0041290285614118951,
  0.0036299537506093767,
  0.0036011632492713563,
  0.0035038834032994287,
  0.003982479433816309,
  0.0034235493937141708,
  0.0032295668758800097,
  0.0031845042347107256,
  0.0032015330741338639,
  0.0033543736708707343,
  0.003352371638501498,
  0.0033282170368132192,
  0.0029689787612862399,
  0.0030349094407615541,
  0.0028124347189876519,
  0.0027767949167499754,
  0.0028542954122177631,
  0.0027381123596297526,
  0.0026814400601400949,
  0.002821325879352533,
  0.0026268315236040642,
  0.0025619766892534552,
  0.0025666546877299514,
  0.0025838100129442518,
  0.0026420041740323618,
  0.0024415611041379032,
  0.002496812042179648,
  0.0023860178178472216,
  0.0023290315538505527,
  0.0023047690275429843,
  0.0022429730677890167,
  0.0022766946175214009,
  0.002268691103313571,
  0.0022091093249009732,
  0.0021367552864286943,
  0.0020821128142823543,
  0.0021595037302924928,
  0.0021435934201614044,
  0.0020092812902076499,
  0.0020613407555131989,
  0.0019626574303571865,
  0.0019339618521141951,
  0.0019405710970042884,
  0.0019008685338580719,
  0.0018521568174343383,
  0.0018980386601673944,
  0.0018981846362770161,
  0.0018847695634500168,
  0.0018443969626710795,
  0.0017644569155908076,
  0.0017569741826051863,
  0.0017317785211255618,
  0.0018742028319181127,
  0.0016937593757566586,
  0.0017292976431618227,
  0.0016889249085596649,
  0.0016742029159860772,
  0.0016511505824365767,
  0.001634834909802912,
  0.0016076314158598396,
  0.0016064693211255787,
  0.0015486289570804373,
  0.0016096201181307296,
  0.0015926077726915061,
  0.0015903484635490263,
  0.0015051037423469335,
  0.0015567711371684743,
  0.0015009063911824443,
  0.0014950939036348712,
  0.0014883193457238028,
  0.0014601607565446018,
  0.001448538428538035,
  0.0014208188785292278,
  0.0014286207200558943,
  0.0013861810422946359,
  0.0013438998427781686,
  0.0013884641153946798,
  0.0013317612704829634,
  0.0013879164531130656,
  0.0013658039959443507,
  0.0013722846465115653,
  0.001335113717321411,
  0.001337423160123839,
  0.0013091386563501485,
  0.001295629324104254,
  0.001338108294756613,
  0.0012844009945064644,
  0.001310495359422726,
  0.0012767100935175179,
  0.0012794886247872888,
  0.0012512179233011937,
  0.0012590954190111398,
  0.0012668399444876986,
  0.001245221728023803],
 'val_acc': [0.69626168280004341,
  0.69626168280004341,
  0.69626168280004341,
  0.69626168280004341,
  0.69626168280004341,
  0.69626168280004341,
  0.69859813139817428,
  0.70093457776809409,
  0.70560747719256678,
  0.70794392579069765,
  0.71028037661703947,
  0.70560747719256678,
  0.70794392579069765,
  0.69158878783199274,
  0.71028037661703947,
  0.70560747719256678,
  0.70794392579069765,
  0.7079439280189086,
  0.70560747942077784,
  0.71028037438882841,
  0.71495327158509014,
  0.70560747942077784,
  0.70794392579069765,
  0.7149532738133012,
  0.71028037438882841,
  0.73130841121495327,
  0.71495326935687908,
  0.71962617045251009,
  0.74532710503194932,
  0.73130840954379506,
  0.70794392356248659,
  0.73598130841121501,
  0.73364486204129509,
  0.73364486204129509,
  0.73598131063942596,
  0.72429906764877172,
  0.7289719626168224,
  0.7219626168224299,
  0.72897196484503346,
  0.72429906764877172,
  0.72429906764877172,
  0.72663551401869164,
  0.72663551624690259,
  0.72429906764877172,
  0.73364486204129509,
  0.7289719626168224,
  0.73364485758487308,
  0.73364486148424235,
  0.73364485758487308,
  0.73598130841121501,
  0.73831775478113482,
  0.73598130841121501,
  0.73130841121495327,
  0.73831775923755683,
  0.73598131063942596,
  0.75000000167115821,
  0.7429906542056075,
  0.74532710447489658,
  0.73831775700934577,
  0.74065420560747663,
  0.73598130841121501,
  0.73831775923755683,
  0.74532710447489658,
  0.73598130618300395,
  0.73831775700934577,
  0.73364485981308414,
  0.74532710447489658,
  0.74299065197739644,
  0.76635514130102145,
  0.73130841121495327,
  0.75000000167115821,
  0.74766354917365818,
  0.74766355307302745,
  0.75700934690849808,
  0.7499999972147362,
  0.74532710224668552,
  0.74065420560747663,
  0.74766355307302745,
  0.74532710057552731,
  0.75233644804107813,
  0.73831775700934577,
  0.74065420337926557,
  0.7570093430091287,
  0.78037383066159538,
  0.76401869047467952,
  0.77336448709541394,
  0.74766355084481639,
  0.75233644859813087,
  0.76635513740165206,
  0.74532710447489658,
  0.75233645026928908,
  0.78738317478482966,
  0.78037383288980644,
  0.76635514130102145,
  0.77336448319604467,
  0.78271028148793731,
  0.76869158599978293,
  0.78738318035535726,
  0.76635513740165206,
  0.77803738429167557,
  0.77102803626907201,
  0.78037383066159538,
  0.76635513907281039,
  0.75934579160725957,
  0.75000000111410547,
  0.78504673008606818,
  0.77803738206346462,
  0.74065420727863485,
  0.77803738206346462,
  0.77570093179417543,
  0.77803738206346462,
  0.78738317645598799,
  0.7710280345979138,
  0.77336448486720288,
  0.75934579160725957,
  0.75233644804107813,
  0.76168224410475971,
  0.77336448876657216,
  0.78971962895348813,
  0.77570093346533375,
  0.76401868880352131,
  0.77102803849728307,
  0.75700934690849808,
  0.75700934523733976,
  0.78504673008606818,
  0.78037383066159538,
  0.76869158989915221,
  0.76401869103173226,
  0.77570093569354481],
 'val_loss': [0.010557004476888714,
  0.0088315309399617046,
  0.011035417415480191,
  0.0047951135044551896,
  0.0044392313738571146,
  0.00479454094561461,
  0.0045892799351468817,
  0.0097312609900102442,
  0.0040116920179435024,
  0.0036451462025223211,
  0.0086399235057635845,
  0.0067556285316768654,
  0.0065744726561775832,
  0.0055226505838473824,
  0.0029529542074686736,
  0.0048700734607387925,
  0.0056075057946145535,
  0.0036177415613990243,
  0.0025412018528364806,
  0.0026814060690421087,
  0.0026372984099576127,
  0.0041393772503099989,
  0.0024740319572841732,
  0.003425485761313934,
  0.0025278093384700677,
  0.0022687726005668116,
  0.0023464734283075712,
  0.0021794862744929358,
  0.0021042714665739613,
  0.0022527893665725382,
  0.0026457022253215034,
  0.0020819191524985236,
  0.003055342277250836,
  0.0026047602709313141,
  0.0019804302648702096,
  0.0022982028378260746,
  0.0019958289720936216,
  0.0019214081939170572,
  0.0019574281629000869,
  0.0019553902332679692,
  0.0019654765666384144,
  0.0018649862831127699,
  0.0019753020045686965,
  0.0019700375785964117,
  0.0033867753950757125,
  0.0025817108727887133,
  0.0022402397034881269,
  0.0017540054830992332,
  0.0017810061924316198,
  0.0021058719117786283,
  0.0020136536908483952,
  0.0017713235884852638,
  0.0018315886552053913,
  0.0017456890379783706,
  0.0019071282129125477,
  0.0017599905231776081,
  0.0016466180236888266,
  0.0017969406930137878,
  0.0018391373978544757,
  0.0025047720409929752,
  0.0016150099266686033,
  0.001606210212171008,
  0.0017125570186996989,
  0.0018668789960548421,
  0.0016813847741164337,
  0.0015597951981439211,
  0.0017915811622515321,
  0.0016089372835165568,
  0.0016918023939409823,
  0.0019367816934153159,
  0.0015415135329310721,
  0.0020053698866253841,
  0.0017300361656435879,
  0.0023475408719452187,
  0.0018009742238846058,
  0.0015926626565317824,
  0.0014493204598863408,
  0.0016132952769452305,
  0.0017332528276090449,
  0.0015273700200595728,
  0.0015746317782099838,
  0.0016070303015376084,
  0.0015512941292025776,
  0.0014655349937171859,
  0.0017545946012033481,
  0.0018504356277810636,
  0.0021435427316246884,
  0.0014580950101785292,
  0.0016481806012740899,
  0.00178053305227588,
  0.0014501221719519974,
  0.0014553464738060241,
  0.0013972966938288272,
  0.0014648189905282353,
  0.0015866941974768153,
  0.0016264652356801329,
  0.0013797976692407348,
  0.0013514040342627841,
  0.0017793155025046701,
  0.0013790057295341497,
  0.0013719027280964166,
  0.0013309765746381795,
  0.0014068678524084041,
  0.0014177676938717889,
  0.001377824420831819,
  0.0013719478189057417,
  0.0017972712178723276,
  0.0014870069860089049,
  0.0014158115367553083,
  0.0013342336871199937,
  0.0014243713954341746,
  0.0013213813996865093,
  0.0013063327054641095,
  0.0013440096126347083,
  0.0013928648430384068,
  0.0015013294988616465,
  0.0014915322018874304,
  0.0013254603281808652,
  0.0014108491454395318,
  0.0016172959253836041,
  0.0013338116543785295,
  0.0013902545906603336,
  0.0013346184908943337,
  0.001369468636036128,
  0.0015986848864095093,
  0.00132522953534934,
  0.0013517295891662764,
  0.0014086040335263466,
  0.0016692060940228751]}

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer: I first read the blog post, as suggested in the instruction, to study the CNN architectures and hyperparameters used in the post. The first architecture I investigated was adapted from the CNN with the deepest architecture presented in the post, defined as

Layer (type) Activation Output Shape
Conv2D None (None, 96, 96, 32)
BatchNormalization None (None, 96, 96, 32)
Activation ReLu (None, 96, 96, 32)
MaxPooling2 None (None, 48, 48, 32)
Dropout (rate=0.1) None (None, 48, 48, 32)
Conv2D None (None, 48, 48, 64)
BatchNormalization None (None, 48, 48, 64)
Activation ReLu (None, 48, 48, 64)
MaxPooling2 None (None, 24, 24, 64)
Dropout (rate=0.2) None (None, 24, 24, 64)
Conv2D None (None, 24, 24, 128)
BatchNormalization None (None, 24, 24, 128)
Activation ReLu (None, 24, 24, 128)
MaxPooling2 None (None, 12, 12, 128)
Dropout (rate=0.3) None (None, 12, 12, 128)
Flatten None (None, 9216)
Dense None (None, 750)
BatchNormalization None (None, 750)
Activation ReLu (None, 750)
Dropout (rate=0.5) None (None, 750)
Dense None (None, 500)
BatchNormalization None (None, 500)
Activation ReLu (None, 500)
Dense None (None, 30)

The architecture, however, increased val_loss from 2 to 20 within the first 3 epochs using Nadam. The reason for poor performance could be the use of BatchNormalization layers and the complexity of the model, i.e., having a large number of weight and bias parameters (~ 9 millions). To test the hypothesis, i) all BatchNormalization layers were removed; ii) one Dense layer was eliminated (having 2 layers of Dense instead of 3 layers); and iii) the Conv2d layers was set to have 16, 32, and 64 channels (depths), respectively, giving ~4 million parameters. This architecture showed a promising result with val_loss reduced from 0.1 to 0.009 within the first 10 epochs.

Other variants were tested to see whether improvement could be achieved, including: i) addition of a BatchNormalization layer as an input layer; ii) use of L1 kernel regularizations in the Conv2D layers with strength 0.001, 0.0001, and 0.00001; iii) use of L1_L2 kernel regularizations in the Conv2D layers with strength 0.001, 0.0001, and 0.00001; and iv) use of L2 kernel regularizations in the Conv2D layers with strength 0.001, 0.0001, and 0.00001. However, none of its varaints yields the better val_loss and val_acc. Thus, the architecture with ~4 million parameters described in the previous paragraph was chosen as the model used in this work.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: I investigated SGD, Adagrad, and Nadam optimizers. The latter two optimizers are capable of automatically adjusting their intrinsic parameters including learning rate and are recommended to have all of their parameters at the default values. On the other hand, the values of the learning rate of SGD inverstigated were lr=0.01 and 0.001 with momentum=0.09, decay=0.1, nesterov=True. All the optimizers performed comparably. Nadam was selected since it reduced val_loss slightly faster than the other two and it does not require fine-tuning of its parameters.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [47]:
## TODO: Visualize the training and validation loss of your neural network
fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.plot(history.history['acc'])
ax1.plot(history.history['val_acc'])
ax1.set_title('Model Accuracy')
ax1.set_ylabel('Accuracy')
ax1.set_xlabel('Epochs')
ax1.legend(['Train', 'Validation'], loc='upper left')

ax2 = fig.add_subplot(122)
ax2.plot(history.history['loss'])
ax2.plot(history.history['val_loss'])
ax2.set_title('Model Loss')
ax2.set_ylabel('Loss')
ax2.set_xlabel('Epochs')
ax2.legend(['Train', 'Validation'], loc='upper right')
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.2)

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: The model was able to evaluate the training data and the validation data with comparable model accuracy and loss, without apparent overfitting or underfitting. In other words, it was simple and general enough to predict facial key points in faces not present in the training data. This could due to the small number of network parameters and the use of Dropout layers.

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [48]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [4]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')


# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_copy = np.copy(image)

# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image_copy)
Out[4]:
<matplotlib.image.AxesImage at 0x214cccaad30>
In [11]:
def face_detection(gray, scale = 1.5, neighbors = 4):

    #Extract the pre-trained face detector
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(gray, scale, neighbors)
    
    return faces


def facial_key_points(image):
    
    image_display = np.copy(image)
    
    # convert color space
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    # face detection
    scale, neighbors = 1.5, 4
    roi_size=(96,96)
    faces = face_detection(gray, scale, neighbors)

    # key point prediction
    for (x,y,w,h) in faces:
        # draw bounding boxes
        cv2.rectangle(image_display, (x,y), (x+w, y+h), (255,0,0),3)

        # normalize faces
        roi_gray = gray[y:y+h, x:x+w]

        # resize face regions
        scale_x = roi_size[0]/roi_gray.shape[0]
        scale_y = roi_size[1]/roi_gray.shape[1]
        scaled_roi_gray = cv2.resize(roi_gray, None,fx=scale_x, fy=scale_y, 
                                     interpolation = cv2.INTER_CUBIC)
        scaled_roi_gray = np.float32(scaled_roi_gray)/255.
        scaled_roi_gray = scaled_roi_gray.reshape((-1,roi_size[0], roi_size[1], 1))

        # predict key points
        key_points = model.predict(scaled_roi_gray)

        #unnormalize key points
        key_points = np.squeeze((48.*key_points)+48.)

        # correct x and x coordinates, respectively
        key_points[0::2] = (key_points[0::2]/scale_x) + x
        key_points[1::2] = (key_points[1::2]/scale_y) + y


        for fx, fy in zip(key_points[0::2], key_points[1::2]):
            cv2.circle(image_display, (fx,fy), 1, (0,255,0), 2)

    return image_display
In [8]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
model.load_weights('saved_models/weights.best_ndam.hdf5')

image_display = facial_key_points(image)
    
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax.set_xticks([])
ax.set_yticks([])
ax.imshow(image_display)
Number of faces detected:  2
Out[8]:
<matplotlib.image.AxesImage at 0x2148aad6eb8>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [9]:
import cv2
import time 
from keras.models import load_model
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        frame = facial_key_points(frame)
        
        # plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [12]:
# Run your keypoint face painter
laptop_camera_go()

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [103]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

print(sunglasses[0,0,0])
#sunglasses[:,:,4] = sunglasses[:,:,1]

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses[:,:,-1] == 255, cmap='gray')
ax1.axis('off');
0

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [14]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [30]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
the alpha channel here looks like
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109], dtype=int64), array([ 687,  688,  689, ..., 2376, 2377, 2378], dtype=int64))
Out[30]:
255

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [16]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[16]:
<matplotlib.image.AxesImage at 0x2148a7df940>
In [100]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

def sun_glasses_overlay(image):
    
    image_display = np.copy(image)
    
    # convert color space
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    # face detection
    scale, neighbors = 1.5, 4
    roi_size=(96,96)
    faces = face_detection(gray, scale, neighbors)

    # key point prediction
    for (x,y,w,h) in faces:

        # normalize faces
        roi_gray = gray[y:y+h, x:x+w]

        # resize face regions
        scale_x = roi_size[0]/roi_gray.shape[0]
        scale_y = roi_size[1]/roi_gray.shape[1]
        scaled_roi_gray = cv2.resize(roi_gray, None,fx=scale_x, fy=scale_y, 
                                     interpolation = cv2.INTER_CUBIC)
        scaled_roi_gray = np.float32(scaled_roi_gray)/255.
        scaled_roi_gray = scaled_roi_gray.reshape((-1,roi_size[0], roi_size[1], 1))

        # predict key points
        key_points = model.predict(scaled_roi_gray)

        #unnormalize key points
        key_points = np.squeeze((48.*key_points)+48.)

        # correct x and x coordinates, respectively
        key_points_x = (key_points[0::2]/scale_x) + x
        key_points_y = (key_points[1::2]/scale_y) + y
    
            
        # rescale sun glass
        enlarge = np.int32(abs(key_points_x[6]-key_points_x[8]))
        sunglasses_w = np.int32(abs(key_points_x[9]-key_points_x[7]))+enlarge//2
        sunglasses_h = np.int32(abs((key_points_y[6]+key_points_y[8])/2-key_points_y[10]))+enlarge//3

        scaled_sunglasses = cv2.resize(sunglasses,(sunglasses_w, sunglasses_h), 
                                       interpolation = cv2.INTER_CUBIC)
        
        # compute blending factors
        alpha = scaled_sunglasses[:,:,-1]//255
        alpha_inv = 1-alpha
    
        # draw sunglasses
        ex = np.int32(key_points_x[9])-(enlarge//4)
        ey = np.int32(key_points_y[9])
        
        for c in range(image_display.shape[-1]):
            image_display[ey:ey+sunglasses_h, ex:ex+sunglasses_w, c] = \
            (alpha * scaled_sunglasses[:, :, c] + alpha_inv *image_display[ey:ey+sunglasses_h, ex:ex+sunglasses_w, c])
        

    return image_display

sunglasses_overlay = sun_glasses_overlay(image)

fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Sunglasses')
ax1.imshow(sunglasses_overlay)
Out[100]:
<matplotlib.image.AxesImage at 0x21495db9198>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [101]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        
        # Add glasses
        frame = sun_glasses_overlay(frame)
        
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [105]:
# Load facial landmark detector model
model.load_weights('saved_models/weights.best_ndam.hdf5')

# Run sunglasses painter
laptop_camera_go()